package email

import (
	"crypto/tls"
	"dc-news/common/global/setting"
	"dc-news/entity"
	"fmt"
	"github.com/jordan-wright/email"
	"go.uber.org/zap"
	"net/smtp"
)

func SendMail(address string, subject string, body string) (err error) {
	em := email.NewEmail()
	em.From = fmt.Sprintf("dc-news Support <%s>", setting.Conf.MailUser)
	em.To = []string{address}
	em.Subject = subject
	em.HTML = []byte(body)
	host := fmt.Sprintf("%s:%s", setting.Conf.MailHost, setting.Conf.MailPort)
	auth := smtp.PlainAuth("", setting.Conf.MailUser, setting.Conf.MailPwd, setting.Conf.MailHost)
	err = em.SendWithTLS(host, auth, &tls.Config{ServerName: "smtp.exmail.qq.com"})
	if err != nil {
		zap.S().Error(err)
	}
	return err
}

// SendResetPasswordEmail 发送重置密码邮件
func SendResetPasswordEmail(user *entity.User, token string) (ok bool) {
	link := fmt.Sprintf("%s/user/password/reset?email=%s&token=%s", setting.Conf.AppDomain, user.Email, token)
	body := fmt.Sprintf(`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
　<head>
　　<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
　　<title>重置密码</title>
　　<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
　</head>
<body>
	<h1">dc-news重置密码</h1>
	<p>尊敬的：%s</p>
	<p>我们收到了一个重置密码的请求，如需重置密码，请<a href="%s">点击此处<a/>，链接30分钟内有效</p>
	<p>如果链接无法跳转，请将该链接复制到浏览器打开：<a href="%s">%s<a/></p>
</body>
</html>
`, user.Username, link, link, link)
	err := SendMail(user.Email, "重置密码", body)
	if err != nil {
		zap.L().Error(err.Error())
		return false
	}
	return true
}

// SentConfirmEmail 发送绑定邮箱邮件
func SentConfirmEmail(user *entity.User, token string) (ok bool) {
	link := fmt.Sprintf("%s/email/confirm?email=%s&token=%s", setting.Conf.AppDomain, user.Email, token)
	body := fmt.Sprintf(`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
　<head>
　　<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
　　<title>绑定邮箱</title>
　　<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
　</head>
<body>
	<h1">dc-news绑定邮箱</h1>
	<p>尊敬的：%s</p>
	<p>请<a href="%s">点击此处<a/>确认绑定该邮箱，链接30分钟内有效</p>
	<p>如果链接无法跳转，请将该链接复制到浏览器打开：<a href="%s">%s<a/></p>
</body>
</html>
`, user.Username, link, link, link)
	err := SendMail(user.Email, "绑定邮箱", body)
	if err != nil {
		zap.L().Error(err.Error())
		return false
	}
	return true
}
